using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace HKB.Alipay
{
	public class Notify
	{
		private string _partner = "";
		private string _key = "";
		private string _input_charset = "";
		private string _sign_type = "";
		private string Https_veryfy_url = "https://mapi.alipay.com/gateway.do?service=notify_verify&";
		public Notify()
		{
			this._partner = Config.Partner.Trim();
			this._key = Config.Key.Trim().ToLower();
			this._input_charset = Config.Input_charset.Trim().ToLower();
			this._sign_type = Config.Sign_type.Trim().ToUpper();
		}
		public bool Verify(SortedDictionary<string, string> inputPara, string notify_id, string sign)
		{
			string responseMysign = this.GetResponseMysign(inputPara);
			string a = "true";
			if (notify_id != "")
			{
				a = this.GetResponseTxt(notify_id);
			}
			return a == "true" && sign == responseMysign;
		}
		private string GetPreSignStr(SortedDictionary<string, string> inputPara)
		{
			Dictionary<string, string> dicArray = new Dictionary<string, string>();
			dicArray = Core.FilterPara(inputPara);
			return Core.CreateLinkString(dicArray);
		}
		private string GetResponseMysign(SortedDictionary<string, string> inputPara)
		{
			Dictionary<string, string> dicArray = new Dictionary<string, string>();
			dicArray = Core.FilterPara(inputPara);
			return Core.BuildMysign(dicArray, this._key, this._sign_type, this._input_charset);
		}
		private string GetResponseTxt(string notify_id)
		{
			string strUrl = string.Concat(new string[]
			{
				this.Https_veryfy_url,
				"partner=",
				this._partner,
				"&notify_id=",
				notify_id
			});
			return this.Get_Http(strUrl, 120000);
		}
		private string Get_Http(string strUrl, int timeout)
		{
			string result;
			try
			{
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);
				httpWebRequest.Timeout = timeout;
				HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
				Stream responseStream = httpWebResponse.GetResponseStream();
				StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
				StringBuilder stringBuilder = new StringBuilder();
				while (-1 != streamReader.Peek())
				{
					stringBuilder.Append(streamReader.ReadLine());
				}
				result = stringBuilder.ToString();
			}
			catch (Exception ex)
			{
				result = "错误：" + ex.Message;
			}
			return result;
		}
	}
}
